<template>
  <div>
    <bread-crumb name1="权限管理" name2="角色列表"></bread-crumb>
    <el-card>
      <el-row>
        <el-col :span="4">
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="rolesList" style="width: 100%" border>
        <el-table-column type="expand">
          <template slot-scope="scoped">
            <div>
              <!-- <p>{{ scoped.row }}</p> -->
              <el-row
                :class="['row-bottom', index1 == 0 ? 'row-top' : '']"
                v-for="(item1, index1) in scoped.row.children"
                :key="item1.id"
              >
                <el-col :span="5">
                  <el-tag
                    closable
                    @close="deleteRightsById(scoped.row, item1.id)"
                    >{{ item1.authName }}</el-tag
                  >
                </el-col>
                <el-col :span="19">
                  <el-row
                    :class="[
                      'row-top',
                      index2 == item1.children.length - 1 ? 'row-bottom' : '',
                    ]"
                    v-for="(item2, index2) in item1.children"
                    :key="item2.id"
                  >
                    <el-col :span="6">
                      <el-tag
                        closable
                        type="success"
                        @close="deleteRightsById(scoped.row, item2.id)"
                        >{{ item2.authName }}</el-tag
                      >
                    </el-col>
                    <el-col :span="18">
                      <el-tag
                        type="danger"
                        v-for="item3 in item2.children"
                        :key="item3.id"
                        closable
                        @close="deleteRightsById(scoped.row, item3.id)"
                        >{{ item3.authName }}</el-tag
                      >
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </div>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scoped">
            <div>
              <p>{{ scoped.row.id }}</p>
              <el-button type="primary" size="mini" icon="el-icon-edit"
                >编辑</el-button
              >
              <el-button type="danger" size="mini" icon="el-icon-delete"
                >删除</el-button
              >
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-search"
                @click="ShowAddRightsDialog(scoped.row)"
                >分配权限</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
      title="权限分配"
      :visible.sync="showRightsTreeDdialogVisible"
      width="50%"
      @closed="clearDefaultKey"
    >
      <!-- :data="data" :props="defaultProps" -->
      <el-tree
        :data="rightsList"
        :props="rightsProps"
        node-key="id"
        show-checkbox
        default-expand-all
        :default-checked-keys="defaultKey"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showRightsTreeDdialogVisible = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="addRights">添加权限</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import BreadCrumb from "@/components/common/breadcrumb/BreadCrumb";
import {
  roles_list_req,
  delete_roles_rights_req,
  roles_add_rights_req,
} from "@/api/roles.js";
import { rights_list_req } from "@/api/rights.js";
export default {
  mounted() {
    // 获取所有角色列表
    this.getRolesList();
  },
  data() {
    return {
      rolesList: [],
      // 控制权限分配的对话框
      showRightsTreeDdialogVisible: false,
      // 分配权限当中的权限列表
      rightsList: [],
      // 配置属性名
      rightsProps: {
        label: "authName",
        children: "children",
      },
      // 默认勾选的id
      // 如何收集角色的权限的id
      defaultKey: [],
      // 角色id
      rolesId: "",
    };
  },
  components: {
    BreadCrumb,
  },
  methods: {
    async getRolesList() {
      const result = await roles_list_req();
      console.log(result);
      if (result.meta.status !== 200) {
        return this.$message.error("请求角色列表失败");
      }
      this.rolesList = result.data;
    },
    /* 
  权限列表中的删除权限的逻辑：
  1.tag组件点击删除对应的事件  经过查文档 @close
  2.接口文档当中是否有对应的删除的接口 有 接口参数
  在api中对应的文件中进行接口分类封装
  需要什么参数  收集参数 传递进来
  3. 去页面当中查找参数，将其传递进入
  4.确认框进行确认
  5.调用接口进行删除
  6.需要刷新数据才能展示最新数据  点开按钮
  没有数据更新的代码  重新调用请求数据的即可即可
  分析你具体更新的是哪里的数据
  对应的该个角色的权限  scoped.row.children中


  


*/
    async deleteRightsById(role, id) {
      console.log(role, id);
      // 弹出提示框 是否删除
      const confirmResult = await this.$confirm(
        "此操作将永久删除该角色权限, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      console.log(confirmResult);
      // 如果确认删除 找接口 封装接口 删除数据
      const result = await delete_roles_rights_req(
        `roles/${role.id}/rights/${id}`
      );
      console.log(result);
      if (result.meta.status !== 200) {
        return this.$message({
          type: "error",
          message: "删除权限失败",
        });
      }
      // 成功之后
      // 但是界面该权限任然显示，刷新页面 界面更新到最新状态 还得再点击一下展开按钮
      //
      // this.getRolesList();
      role.children = result.data;
    },
    async ShowAddRightsDialog(roles) {
      this.rolesId = roles.id;
      // 展示dialog数据就应该请求回来
      const result = await rights_list_req({
        method: "get",
        url: "rights/tree",
      });
      console.log(result);
      //失败
      if (result.meta.status !== 200) {
        return this.$message.error("获取权限列表失败");
      }
      // 成功
      this.rightsList = result.data;

      // 该角色默认应该有的权限
      console.log(roles);
      this.getKey(this.defaultKey, roles);

      // 展示
      this.showRightsTreeDdialogVisible = true;
    },
    // 获取三级列表id
    // arr: 盛放收集的id 的新数组
    // rolesRightsList 角色的列表
    getKey(arr, rolesRightsList) {
      console.log(rolesRightsList);
      // 递归的结束条件
      if (!rolesRightsList.children) {
        console.log(11111);
        console.log(arr);

        return arr.push(rolesRightsList.id);
      }
      rolesRightsList.children.forEach((element) => {
        this.getKey(arr, element);
      });
    },
    clearDefaultKey() {
      this.defaultKey = [];
    },
    /* 
    添加权限  在复选框当中勾选  id 

    界面操作完毕之后 需要更新服务器当中的权限
    接口
    roles/:roleId/rights
    请求方法：post
    roleId  作用域插槽 role scloped.row.id
    rids  '105,110,112'

    getCheckedKeys 获取全选的key
    getHalfCheckedKeys 获取半选的key




    */
    async addRights() {
      console.log(this.$refs.treeRef.getCheckedKeys());
      console.log(this.$refs.treeRef.getHalfCheckedKeys());
      const keyStr = this.$refs.treeRef
        .getCheckedKeys()
        .concat(this.$refs.treeRef.getHalfCheckedKeys())
        .join(",");
      console.log(keyStr);

      // 发送请求
      const result = await roles_add_rights_req({
        method: "post",
        url: `roles/${this.rolesId}/rights`,
        data: {
          rids: keyStr,
        },
      });
      console.log(result);
      if (result.meta.status !== 200) {
        return this.$message.error("更新权限失败");
      }
      this.$message.success("添加权限成功！！");
      // 更新
      this.getRolesList();
      //  对话框关闭
      this.showRightsTreeDdialogVisible = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.el-tag {
  margin: 10px;
}
.row-top {
  border-top: 1px solid #ccc;
}
.row-bottom {
  border-bottom: 1px solid #ccc;
}
</style>